
import sys
from PyQt5.QtWidgets import (
    QApplication, QWidget, QVBoxLayout, QTextEdit,  # QLineEdit 替换为 QTextEdit
    QPushButton, QLabel, QMessageBox)
from PyQt5.QtGui import ( QPixmap, QPainter, QColor,QFont  )
from PyQt5.QtCore import Qt, QRectF # QRect 替换为 QRectF 更适合文档绘制

class TextToBitmapApp(QWidget):
    def __init__(self):
        super().__init__()
        self.bitmap_width = 384  # 固定宽度
        self.initUI()

    def initUI(self):
        self.setWindowTitle(f'黑马嵌入式')
        self.setGeometry(300, 300, 400, 500) # 增加了窗口高度以容纳多行输入框

        layout = QVBoxLayout()

        self.input_text = QTextEdit()  # 使用 QTextEdit
        self.input_text.setFont(QFont("微软雅黑", 14))
        self.input_text.setPlaceholderText("在此输入多行文本...\n")
       
        self.generate_button = QPushButton('打印文本')
        self.generate_button.clicked.connect(self.create_bitmap)

        self.image_label = QLabel('生成的图片会显示在这里')
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setMinimumHeight(150) # 给图片预览留出一些空间

        layout.addWidget(QLabel("输入内容:"))
        layout.addWidget(self.input_text)
        layout.addWidget(self.generate_button)
        layout.addWidget(QLabel("预览:"))
        layout.addWidget(self.image_label)

        self.setLayout(layout)

    def create_bitmap(self):
        # 0. 获取 QTextEdit 的文档
        source_doc = self.input_text.document()
        if source_doc.isEmpty() or source_doc.toPlainText().strip() == "":
            QMessageBox.warning(self, "警告", "请输入有效内容！")
            return

        # 1. 克隆文档并获取样式属性
        doc_to_draw = source_doc.clone() # 克隆文档以保留格式
        


        # 2. 设置文档宽度并计算图片高度
        # 关键：设置文档的文本宽度，QTextDocument会据此处理换行
        doc_to_draw.setTextWidth(float(self.bitmap_width))
        
        # 获取文档在设定宽度下实际需要的高度
        content_height = int(doc_to_draw.size().height())

        # 如果内容为空字符串但文档不为空（例如只有换行符），或者高度计算为0但有内容
        if content_height == 0:
             QMessageBox.warning(self, "警告", "请输入有效内容！")
             return

        padding = 10 # 上下各5px的padding
        bitmap_height = content_height + padding

        # 3. 创建QPixmap并准备QPainter
        pixmap = QPixmap(self.bitmap_width, bitmap_height)
        pixmap.fill(QColor("white"))

        painter = QPainter(pixmap)
        
        # 4. 绘制QTextDocument
        # 将文档内容绘制到 QPixmap 上
        doc_to_draw.drawContents(painter)
        
        painter.end()

        # 5. 显示和保存图片
        self.image_label.setPixmap(pixmap.scaled(
            self.image_label.width(), self.image_label.height(),
            Qt.KeepAspectRatio, Qt.SmoothTransformation
        ))

        file_path = "generated_bitmap_multiline.png"

        if file_path:
            if not pixmap.save(file_path):
                QMessageBox.critical(self, "错误", f"无法保存图片到 {file_path}")
            else:
                QMessageBox.information(self, "成功", f"图片已保存到 {file_path}")
        
        from dither import dither_image,send_to_printer
        img = dither_image("generated_bitmap_multiline.png", "generated_bitmap_multiline.bmp")
        send_to_printer(img,port="COM3")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = TextToBitmapApp()
    ex.show()
    sys.exit(app.exec_())